//
//  HMEveryDayViewCtr.m
//  HowToDo
//
//  Created by 胡坤 on 2017/1/6.
//  Copyright © 2017年 KY. All rights reserved.
//

#import "HMEveryDayViewCtr.h"
#import "HMSCChannelView.h"
#import "HMListenAnyTimeResModel.h"
#import "HMEveryDayViewModel.h"
#import "HMEveryDayListTabCell.h"
#import "HMFASheetView.h"
#import "HMFABottomBar.h"
#import "HMTEDListPopView.h"
#import "UITableView+refreshControl.h"
#import "HMEVDateGroup.h"
@interface HMEveryDayViewCtr ()<UITableViewDataSource,UITableViewDelegate>
/**
 顶部频道
 */
@property(nonatomic,strong)HMSCChannelView *topChannelView;

/**
 涨知识页面对应的VM
 */
@property(nonatomic,strong)HMEveryDayViewModel *everyDayVM;

/**
 点击cell上辅助按钮弹出的小功能view
 */
@property(nonatomic,strong)HMFASheetView *sheetView;
/*
 *底部bar
 **/
@property(nonatomic,strong)HMFABottomBar* loadBar;
@property(nonatomic,strong)UIView *coverView;
@property(nonatomic,strong)HMTEDListPopView* listPopView;
@property(nonatomic,strong)NSMutableDictionary *downLoadUrlCache;
@property(nonatomic,assign)long long totalSize;
@property(nonatomic,strong)UITableView * tableView;
@end
static NSString* EveryDayTabCellID = @"EveryDayTabCellID ";
@implementation HMEveryDayViewCtr

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUPUI];
    [self loadData];
}

#pragma mark --dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.everyDayVM.freeaudioList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HMEVDateGroup* dataGroup = self.everyDayVM.freeaudioList[section];
    return dataGroup.freeAudioList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HMEveryDayListTabCell * cell = [tableView dequeueReusableCellWithIdentifier: EveryDayTabCellID forIndexPath:indexPath];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    HMEVDateGroup* dataGroup = self.everyDayVM.freeaudioList[indexPath.section];
    HMListenAnyTimeResModel *freeAudio = dataGroup.freeAudioList[indexPath.row];
    cell.freeAudio = freeAudio;
    //点击cell上的按钮弹出更多功能按钮的方法
    [self CreatNewSheetViewOrCollectOldSheetViewWhenCilckCell:cell];
    //记录和取消要下载的数据信息的方法
    [self addOrTakeAwayAlreadyaddWithCell:cell];
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    HMEVDateGroup* dataGroup = self.everyDayVM.freeaudioList[section];
    return dataGroup.dayTime;
}
#pragma mark -- delegate
#pragma mark --当编辑模式时选中和取消选中的响应事件
//记录和取消要下载的数据信息的方法
-(void)addOrTakeAwayAlreadyaddWithCell:(HMEveryDayListTabCell*)cell
{
    __weak typeof(self)weakSelf = self;
    cell.selectFileToLoad = ^(HMEveryDayListTabCell * currentCell, HMListenAnyTimeResModel *audio, BOOL isSelected)
    {
        NSIndexPath * indexPath = [weakSelf.tableView indexPathForCell:currentCell];
        NSString* key = [NSString stringWithFormat:@"%zd%zd",indexPath.section,indexPath.row];
        HMEveryDayListTabCell * downCell = [weakSelf.downLoadUrlCache objectForKey:key];
        if (isSelected && downCell == nil)
        {
            //当本地缓存没有时保存，
            if (downCell  == nil)
            {
                [weakSelf.downLoadUrlCache setObject:currentCell forKey:key];
            }
        }else if (!isSelected && downCell != nil)
        {
            [weakSelf.downLoadUrlCache removeObjectForKey:downCell];
        }
    };
}
//回收sheetView或者创建
- (void)CreatNewSheetViewOrCollectOldSheetViewWhenCilckCell:(HMEveryDayListTabCell *)cell
{
    __weak typeof(self)weakSelf = self;
    cell.clickAccessoryView = ^(UIButton *sender,HMEveryDayListTabCell *cell)
    {
        if (weakSelf.sheetView)
        {
            [weakSelf.sheetView removeFromSuperview];
            weakSelf.sheetView = nil;
        }else
        {
            //获取当前按钮在所在cell的tabView上的位置
            CGRect frame = [weakSelf.tableView convertRect:sender.frame fromView:cell];
            //获取中心点
            CGPoint point = [weakSelf.tableView convertPoint:sender.center fromView:cell];
            //创建新的sheetView
            HMFASheetView* sheetView = [HMFASheetView loadNibView];
#pragma mark --点击分享，点赞，列表响应的方法
            sheetView.clickFunctionBtn = ^(buttonName name)
            {
                switch (name)
                {
                    case FunctionList:
                    {
                        NSLog(@"列表");
                    }
                        break;
                    case Functionlike:
                    {
                        NSLog(@"点赞");
                    }
                        break;
                    case FunctionShare:
                    {
                        NSLog(@"分享");
                        [[HMNetWorkTool sharedTool]shareTextToPlatformType:1 andShareMessage:@"欢迎使用HUODE"];
                    }
                        break;
                    default:
                        break;
                }
            };
            //设置pop出来的视图大小
            CGFloat width = 210;
            CGFloat height = 70;
            //设置初始位置和初始大小
            sheetView.frame  = CGRectMake(CGRectGetMinX(frame), point.y - height* 0.5, 0, height);
            [self.tableView addSubview:sheetView];
            //设置动画效果
            [UIView animateWithDuration:0.25 animations:^{
                sheetView.frame = CGRectMake(CGRectGetMinX(frame)-width,  point.y - height* 0.5, width, height);
            }];
            weakSelf.sheetView = sheetView;
        }
    };
}
//让蒙板出现
-(void)popViewWillApper
{
    [self.view.window addSubview:self.coverView];
    [self.view.window insertSubview:self.listPopView aboveSubview:self.coverView];
    [UIView animateWithDuration:0.25 animations:^
     {
         self.coverView.alpha = 1;
         self.listPopView.frame = CGRectMake(0, 88, HMSCREEN_WIDTH, HMSCREEN_HEIGHT - 88);
     }];
    __weak typeof(self)weakSelf = self;
    self.listPopView.dismissActionPerform = ^
    {
        [weakSelf dismissPopView];
    };
}
//去掉蒙板
-(void)dismissPopView
{
    [UIView animateWithDuration:0.25 animations:^
     {
         self.listPopView.frame = CGRectMake(0, HMSCREEN_HEIGHT, HMSCREEN_WIDTH, HMSCREEN_HEIGHT - 88);
         self.coverView.alpha = 0;
         
     }completion:^(BOOL finished)
     {
         [self.listPopView removeFromSuperview];
         [self.coverView removeFromSuperview];
         self.listPopView = nil;
         self.coverView = nil;
     }];
}
//点击头部列表按钮调用的方法
-(void)performTopListButtonAction
{
    if (self.sheetView)
    {
        [self.sheetView removeFromSuperview];
        self.sheetView = nil;
    }
    else
    {
        //点击列表。弹出蒙板，并充下方展示出来一个列表
        [self popViewWillApper];
    }
}
//---------------顶部频道标签的事件----
#pragma  mark --配置UI界面
-(void)setUPUI
{
    //添加顶部标签视图
    [self.view addSubview:self.topChannelView];
    [self.topChannelView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.top.equalTo(self.view).mas_offset(64);
         make.leading.trailing.equalTo(self.view);
         make.height.mas_equalTo(HMBOTTOMBAR_HEIGHT);
     }];
    //  设置tableView
    [self setupTableView];
    //底部视图初始布局
    [self.view insertSubview:self.loadBar aboveSubview:self.tableView];
    [self.loadBar mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.right.equalTo(self.view);
         make.top.equalTo(self.view.mas_bottom);
         make.height.mas_equalTo(49);
     }];
    //--点击头部频道标签的回调
    __weak typeof(self)weakSelf = self;
    self.topChannelView.clickListBtn =^
    {
        [weakSelf performTopListButtonAction];
    };
    self.topChannelView.clickFunctionBtn = ^(BOOL isSelected)
    {
        if (weakSelf.sheetView)
        {
             [weakSelf.sheetView removeFromSuperview];
              weakSelf.sheetView = nil;
              weakSelf.topChannelView.isLoading = NO;
        }else
        {
            weakSelf.tableView.editing = isSelected;
            //设置动画效果
            [UIView animateWithDuration:0.25 animations:^
             {
                 [weakSelf.loadBar mas_updateConstraints:^(MASConstraintMaker *make)
                  {
                      make.top.equalTo(weakSelf.view.mas_bottom).mas_offset(isSelected?-49:0);
                  }];
             }];
         }
    };
    //底部下载按钮的响应事件回调
    self.loadBar.loadSelectedAudioFiles = ^
    {
        HMLog(@"已选择下载%zd首歌曲",weakSelf.downLoadUrlCache.count);
        weakSelf.topChannelView.isLoading = YES;
        [weakSelf downLoadWithCache:weakSelf.downLoadUrlCache];
    };
}
#pragma mark  --请求数据的方法
- (void)loadData
{
    __weak typeof(self)weakSelf  = self;
    [self.everyDayVM requestFreeAudioListFinished:^(NSError *error)
    {
        if (error !=nil)
        {
            NSLog(@"%@",error);
        }else
        {
            //只有请求到数据时才可以调用这个方法，要不然，block未实现会崩溃
            [weakSelf.tableView reloadData];
            [weakSelf.tableView  endPullUPRefresh];
        }
    }];
}
- (void)setupTableView
{
    self.automaticallyAdjustsScrollViewInsets = false;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[HMEveryDayListTabCell class] forCellReuseIdentifier:EveryDayTabCellID];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 100;
    [self.tableView addTableViewRefreshFooterWhenPullToPerformAction:@selector(loadData)];
}

#pragma mark -- 开始上拉加载
- (void)startFootRefreshing
{
    [self loadData];
}
//点击下载按钮是调用的方法
- (void)downLoadWithCache:(NSMutableDictionary*)downLoadCace
{
    __weak typeof(self)weakSelf = self;
   [downLoadCace enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop)
  {
      HMEveryDayListTabCell* cell = (HMEveryDayListTabCell*) obj;
      HMListenAnyTimeResModel *freeAudio = cell.freeAudio;
      [weakSelf.everyDayVM downLoadMp3FileWithFreeAudio:freeAudio progress:^(float progress)
      {
          cell.progress = progress;
          
      } completion:^(NSString *filePath)
      {
          HMLog(@"%@",filePath);
      }];
      long long size = freeAudio.file_size.longLongValue/(1024*1024);
      weakSelf.totalSize += size;
  }];
     NSString * info = [NSString stringWithFormat:@"总共下载%zd件 共计%zdM", downLoadCace.count,self.totalSize];
    self.loadBar.fileInfo = info;
}
#pragma MARK ---懒加载
- (HMSCChannelView *)topChannelView
{
    if (!_topChannelView)
    {
        _topChannelView = [[HMSCChannelView alloc]init];
    }
    return _topChannelView;
}
- (HMEveryDayViewModel *)everyDayVM
{
    if (!_everyDayVM)
    {
        _everyDayVM = [[HMEveryDayViewModel alloc]init];
    }
    return _everyDayVM;
}
- (HMFABottomBar *)loadBar
{
    if (!_loadBar)
    {
        _loadBar = [HMFABottomBar loadNibView];
    }
    return _loadBar;
}
- (UIView *)coverView
{
    if (!_coverView)
    {
        _coverView = [[UIView alloc]initWithFrame:self.view.window.bounds];
        _coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
        _coverView.alpha = 0;
    }
    return _coverView;
}
- (HMTEDListPopView *)listPopView
{
    if (!_listPopView)
    {
        _listPopView = [[HMTEDListPopView alloc]initWithFrame:CGRectMake(0, HMSCREEN_HEIGHT, HMSCREEN_WIDTH, HMSCREEN_HEIGHT - 88)];
    }
    return _listPopView;
}
- (NSMutableDictionary *)downLoadUrlCache
{
    if (!_downLoadUrlCache)
    {
        _downLoadUrlCache = [NSMutableDictionary dictionary];
    }
    return _downLoadUrlCache;
}
- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+49, self.view.bounds.size.width, self.view.bounds.size.height-64-49) style:UITableViewStylePlain];
    }
    return _tableView;
}
@end
